#!/usr/bin/env python3
"""
调试FFmpeg问题
"""

import asyncio
import subprocess
from pathlib import Path

async def test_ffmpeg_commands():
    """测试FFmpeg命令"""
    
    # 测试视频文件
    video_path = Path("uploads/90e15f07-59de-4250-b611-f1cbc6940acc.mp4")
    
    if not video_path.exists():
        print(f"❌ 视频文件不存在: {video_path}")
        return
    
    print(f"🧪 测试FFmpeg命令")
    print(f"📹 视频文件: {video_path}")
    
    # 1. 测试FFmpeg是否可用
    print(f"\n1️⃣ 测试FFmpeg可用性...")
    try:
        result = subprocess.run(['ffmpeg', '-version'], 
                              capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            print(f"   ✅ FFmpeg可用")
            print(f"   版本信息: {result.stdout.split('\\n')[0]}")
        else:
            print(f"   ❌ FFmpeg不可用: {result.stderr}")
            return
    except Exception as e:
        print(f"   ❌ FFmpeg测试失败: {e}")
        return
    
    # 2. 测试获取视频信息
    print(f"\n2️⃣ 测试获取视频信息...")
    try:
        cmd = [
            'ffprobe', '-v', 'quiet', '-print_format', 'json', 
            '-show_format', '-show_streams', str(video_path)
        ]
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        if result.returncode == 0:
            print(f"   ✅ 视频信息获取成功")
            import json
            info = json.loads(result.stdout)
            duration = float(info['format']['duration'])
            print(f"   视频时长: {duration:.1f}秒")
        else:
            print(f"   ❌ 视频信息获取失败: {result.stderr}")
    except Exception as e:
        print(f"   ❌ 视频信息测试失败: {e}")
    
    # 3. 测试简单的视频切分
    print(f"\n3️⃣ 测试视频切分...")
    
    # 创建输出目录
    output_dir = Path("uploads/segments/debug_test")
    output_dir.mkdir(parents=True, exist_ok=True)
    output_path = output_dir / "test_segment.mp4"
    
    try:
        # 简单的切分命令：提取前10秒
        cmd = [
            'ffmpeg', '-i', str(video_path),
            '-ss', '0', '-t', '10',
            '-c', 'copy', '-avoid_negative_ts', 'make_zero',
            '-y', str(output_path)
        ]
        
        print(f"   执行命令: {' '.join(cmd)}")
        
        # 使用asyncio执行
        process = await asyncio.create_subprocess_exec(
            *cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )
        
        stdout, stderr = await process.communicate()
        
        if process.returncode == 0 and output_path.exists():
            file_size = output_path.stat().st_size
            print(f"   ✅ 视频切分成功: {output_path} (大小: {file_size} bytes)")
        else:
            stderr_text = stderr.decode('utf-8', errors='ignore')
            stdout_text = stdout.decode('utf-8', errors='ignore')
            print(f"   ❌ 视频切分失败 (返回码: {process.returncode})")
            print(f"   stderr: {stderr_text}")
            print(f"   stdout: {stdout_text}")
            print(f"   输出文件存在: {output_path.exists()}")
            
    except Exception as e:
        print(f"   ❌ 视频切分测试失败: {e}")
        import traceback
        traceback.print_exc()
    
    # 4. 测试原始的切分参数
    print(f"\n4️⃣ 测试原始切分参数...")
    
    output_path2 = output_dir / "test_segment2.mp4"
    
    try:
        # 使用原始日志中的参数
        cmd = [
            'ffmpeg', '-i', str(video_path),
            '-ss', '0.0', '-t', '59.607142857142854',
            '-c', 'copy', '-avoid_negative_ts', 'make_zero',
            '-y', str(output_path2)
        ]
        
        print(f"   执行命令: {' '.join(cmd)}")
        
        process = await asyncio.create_subprocess_exec(
            *cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )
        
        stdout, stderr = await process.communicate()
        
        if process.returncode == 0 and output_path2.exists():
            file_size = output_path2.stat().st_size
            print(f"   ✅ 原始参数切分成功: {output_path2} (大小: {file_size} bytes)")
        else:
            stderr_text = stderr.decode('utf-8', errors='ignore')
            stdout_text = stdout.decode('utf-8', errors='ignore')
            print(f"   ❌ 原始参数切分失败 (返回码: {process.returncode})")
            print(f"   stderr: {stderr_text}")
            print(f"   stdout: {stdout_text}")
            
    except Exception as e:
        print(f"   ❌ 原始参数测试失败: {e}")

if __name__ == "__main__":
    asyncio.run(test_ffmpeg_commands())